package simi;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;


public class FileUploadServlet extends HttpServlet { 

	private static final long serialVersionUID = -7142207733576737650L;
	//private static final String FORWARD_PAGE = "files.jsp";
	private static final String FORWARD_PAGE = "Browser.jsp";
	private static final String ERROR_PAGE = "error.jsp";
	
	public void doPost(HttpServletRequest req, HttpServletResponse res) { 
		
		String context="";
		String homedir="";

		try{
		
			// first check if the upload request coming in is a multipart request
			boolean isMultipart = FileUpload.isMultipartContent(req);		

			DiskFileUpload upload = new DiskFileUpload();
			    
			// parse this request by the handler
			// this gives us a list of items from the request
			List items = upload.parseRequest(req);
			
			Iterator itr = items.iterator();
			
			while(itr.hasNext()) {
				
				FileItem item = (FileItem) itr.next();
			        
				// check if the current item is a form field or an uploaded file
				if(item.isFormField()) {

				} else {
			
					// the item must be an uploaded file save it to disk. Note that there
					// seems to be a bug in item.getName() as it returns the full path on
					// the client's machine for the uploaded file name, instead of the file
					// name only. To overcome that, I have used a workaround using
					// fullFile.getName().
				
					File fullFile  = new File(item.getName());  
					homedir = (String)req.getSession().getAttribute("homedir");
					context = (String)req.getParameter("context");
					if(context == null){
						context = homedir;
					}
					//trap bad context
					if(! new File(context).getCanonicalPath().startsWith(
							new File(homedir).getCanonicalPath())){
						throw new Exception("path is not nested in home directory");
					}
					
					/* This is a problem - savedFile must have the user's permissions*/
					File savedFile = new File(context, fullFile.getName());
					item.write(savedFile);
				}
			}
			// Forward to the view page
			getServletConfig().getServletContext().getRequestDispatcher(
				FORWARD_PAGE).forward(req,res); 
		}catch(Exception e) {
			try { 
				req.getSession().setAttribute("error",e.toString());
				getServletConfig().getServletContext().getRequestDispatcher(
					ERROR_PAGE).forward(req,res);  
			}catch(Exception e2){ }
		}
	}
}